/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IDE_formularios;

import ConexaoDados.ConexaoMySQL;
import ConexaoDados.InteracaoDados;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;


/**
 *
 * @author erikjan
 */
public class ConsultaServidor extends javax.swing.JFrame {

    public static DefaultTableModel FormataDadosTabela(ResultSet rs){
    try{
            DefaultTableModel dtm = new DefaultTableModel();
            ResultSetMetaData meta = rs.getMetaData();
            int col = meta.getColumnCount();
 
            rs.last();
            int row = rs.getRow();
            rs.beforeFirst();
 
            Object[] rowData = new Object[col];
            Object[] colData = new Object[col];
 
            
            
                colData[0] = "Id Servidor";
                colData[1] = "Nome";
                colData[2] = "Host";
                colData[3] = "Nó";
                colData[4] = "Status";
                colData[5] = "Tempo Leitura (ms)";
                colData[6] = "Tempo Avaliação(horas)";
            
 
            dtm.setColumnIdentifiers(colData);
            
 
            for (int i=0;i<row;i++){
                rs.next();
                for (int j=0;j<col;j++){
                    rowData[j] = rs.getString(j+1);
                }
                dtm.addRow(rowData);
            }
 
            return dtm;//retorna os dados no modelo para tabela - Jtable
            
            
            
    } catch (Exception ex){
        JOptionPane.showMessageDialog(null, "Conveter ResultSet para TableModel : "+ex.getMessage());
        return null;
    }
}
    
    
    
    
    /**
     * Creates new form ConsultaServidor
     */
    public ConsultaServidor() throws SQLException {
        initComponents();
        
        Vector data = new Vector();
        //rotina para fazer consulta e mostrar dados no jTable 
        InteracaoDados dados = new InteracaoDados();
        ResultSet retorno_sql = dados.consulta("select * from servidoropc");
        ResultSetMetaData metaData = retorno_sql.getMetaData();
        int columns = metaData.getColumnCount();
        
        while (retorno_sql.next()) {
                Vector row = new Vector(columns);
                for (int i = 1; i <= columns; i++) {
                    row.addElement(retorno_sql.getObject(i));
                }
                data.addElement(row);
            }
        
        DefaultTableModel dtm = FormataDadosTabela(retorno_sql);
        jTableServidor.setModel(dtm);
        retorno_sql.close();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableServidor = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Lista de Servidores");

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTableServidor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Id Servidor", "Nome", "Host", "No", "Ativo", "Tempo Leitura (ms)", "Tempo Avaliação (horas)"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTableServidor);
        jTableServidor.getColumnModel().getColumn(0).setPreferredWidth(80);
        jTableServidor.getColumnModel().getColumn(1).setPreferredWidth(200);
        jTableServidor.getColumnModel().getColumn(2).setPreferredWidth(100);
        jTableServidor.getColumnModel().getColumn(5).setPreferredWidth(100);
        jTableServidor.getColumnModel().getColumn(6).setPreferredWidth(100);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConsultaServidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConsultaServidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConsultaServidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConsultaServidor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new ConsultaServidor().setVisible(true);
                } catch (SQLException ex) {
                    Logger.getLogger(ConsultaServidor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTableServidor;
    // End of variables declaration//GEN-END:variables
}
